package cn.wangliang181230.boot.unweb.task;

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;

@Component
public class MyTask {

	private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");


	/**
	 * 每5秒执行一次
	 * 每运行一次，消耗1个线程，直到一次运行结束，释放线程。
	 */
	@Scheduled(cron = "0/5 * * * * ?")
	public void task1() throws InterruptedException {
		System.out.println(Thread.currentThread().getId() + "\t" + sdf.format(new Date()) + ": task1: start");
		Thread.sleep(10 * 1000);
		System.out.println(Thread.currentThread().getId() + "\t" + sdf.format(new Date()) + ": task1: end");
	}

	/**
	 * 距上次运行结束，间隔5秒后再执行一次
	 * 每运行一次，消耗1个线程，直到一次运行结束，释放线程。
	 * 注意：会存在线程池耗尽的风险。
	 */
	@Scheduled(fixedRate = 1000 * 5)
	public void task2() throws InterruptedException {
		System.out.println(Thread.currentThread().getId() + "\t" + sdf.format(new Date()) + ": task2: start");
		Thread.sleep(10 * 1000);
		System.out.println(Thread.currentThread().getId() + "\t" + sdf.format(new Date()) + ": task2: end");
	}

	/**
	 * 距上次运行结束，间隔5秒后再执行一次
	 * 同一时间，最多只会有一个任务正在运行，最多消耗1个线程
	 */
	@Scheduled(fixedDelay = 1000 * 5)
	public void task3() throws InterruptedException {
		System.out.println(Thread.currentThread().getId() + "\t\t" + sdf.format(new Date()) + ": task3: start");
		Thread.sleep(10 * 1000);
		System.out.println(Thread.currentThread().getId() + "\t\t" + sdf.format(new Date()) + ": task3: end");
	}

}
